<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <el-alert
        title="注意：只允许为第三级分类设置相关参数"
        type="warning"
        :closable="false"
        show-icon
      >
      </el-alert>
      <el-row>
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader
            v-model="selectedCateId"
            :options="cateList"
            :props="{
              expandTrigger: 'hover',
              label: 'cat_name',
              value: 'cat_id',
            }"
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>

      <!-- 商品参数区域 -->
      <el-tabs v-model="activeName" @tab-click="handleTapClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" :disabled="isDisable" @click="addParam"
            >添加参数</el-button
          >
          <!-- 动态参数区域 -->
          <el-table :data="manyTableData" stripe border>
            <el-table-column type="expand" label="">
              <template #default="scope">
                <el-tag
                  closable
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  @close="closedTag(scope.row, index)"
                >
                  {{ item }}
                </el-tag>

                <!-- tag 标签与文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template #default="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row.cat_id, scope.row.attr_id)"
                  >修改</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleteParams(scope.row.cat_id, scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 静态属性区域 -->

        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" :disabled="isDisable" @click="addParam"
            >添加属性</el-button
          >
          <el-table :data="onlyTableData" stripe border>
            <el-table-column type="expand" label="">
              <template #default="scope">
                <el-tag
                  closable
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  @close="closedTag(scope.row, index)"
                >
                  {{ item }}
                </el-tag>
                <!-- tag 标签与文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column
              label="属性名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template #default="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row.cat_id, scope.row.attr_id)"
                  >修改</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleteParams(scope.row.cat_id, scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加参数对话框 -->
    <el-dialog
      :title="activeName === 'many' ? '添加动态参数' : '添加静态属性'"
      :visible.sync="addAttrDialogVisible"
      width="50%"
      @close="addAttrDialogClosed"
    >
      <!-- 添加参数对话框内容区域 -->
      <el-form
        :model="addAttrForm"
        :rules="addAttrRules"
        ref="addAttrFormRef"
        label-width="100px"
      >
        <el-form-item
          :label="activeName === 'many' ? '动态参数' : '静态属性'"
          prop="attr_name"
        >
          <el-input v-model="addAttrForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addAttrDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="senAddAttrForm">确 定</el-button>
      </span>
    </el-dialog>

    <!--  编辑参数对话框区域 -->
    <el-dialog
      :title="activeName === 'many' ? '修改动态参数' : '修改静态属性'"
      :visible.sync="editAttrDialogVisible"
      width="50%"
      @close="editAttrDialogClosed"
    >
      <el-form
        :model="editAttrForm"
        :rules="addAttrRules"
        ref="editAttrFormRef"
        label-width="100px"
      >
        <el-form-item
          :label="activeName === 'many' ? '动态参数' : '静态属性'"
          prop="attr_name"
        >
          <el-input v-model="editAttrForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editAttrDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="sendEditAttrForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
    
<script>
export default {
  data() {
    return {
      // 商品分类数据
      cateList: [],
      // 选中商品分类 id 数据
      selectedCateId: [],

      // 默认显示的标签页
      activeName: "many",

      // 动态参数数据
      manyTableData: [],

      // 静态属性数据
      onlyTableData: [],

      addAttrDialogVisible: false, // 添加参数对话框关闭与隐藏

      // 添加参数对话框数据
      addAttrForm: {
        attr_name: "",
      },

      editAttrDialogVisible: false, // 编辑参数对话框显示与隐藏

      // 编辑参数数据
      editAttrForm: {
        attr_name: "",
      },

      // 当前编辑参数分类id
      currentCateId: null,
      // 当前编辑参数属性id
      currentAttrId: null,

      // 添加参数对话框表单验证规则
      addAttrRules: {
        attr_name: [
          {
            required: true,
            message: "请输入内容",
            trigger: "blur",
          },
          { min: 1, max: 5, message: "长度在 1 到 5 个字符", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    // 获取商品分类数据
    async getCateList() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status !== 200) {
        return this.$message.error("获取商品分类失败");
      }
      this.cateList = res.data;
    },
    // 监听级联选择框变化事件 获取商品 cat_id
    async handleChange() {
      this.getParamsData();
    },
    // 监听 tabs 变化事件
    handleTapClick() {
      this.getParamsData();
    },

    // 获取参数的列表数据
    async getParamsData() {
      // 证明选中的不是三级分类
      if (this.selectedCateId.length !== 3) {
        this.selectedCateId = [];
        // 对动态参数 静态属性表格数据进行清空
        this.manyTableData = [];
        this.onlyTableData = [];
        return;
      }

      // 证明选中的是三级分类
      //   console.log(this.selectedCateId);
      // 根据所选分类的Id，和当前所处的面板，获取对应的参数
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: this.activeName },
        }
      );

      if (res.meta.status !== 200) {
        return this.$message.error("获取参数列表失败！");
      }

      //将attr_vals 转化为数组
      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(",") : [];

        // 为 item 添加 inputVisible inputValue 属性避免出现数据共用
        item.inputVisible = false;
        item.inputValue = "";
      });
      // console.log(res);

      // 判断是动态参数还是静态属性 分别存储
      if (this.activeName === "many") {
        this.manyTableData = res.data;
      } else {
        this.onlyTableData = res.data;
      }
    },
    // 添加参数事件
    addParam() {
      this.addAttrDialogVisible = true;
      console.log(this.activeName);
    },

    // 监听添加参数对话框关闭事件
    addAttrDialogClosed() {
      this.$refs.addAttrFormRef.resetFields();
    },

    // 点击确定 发送添加参数请求
    senAddAttrForm() {
      // 发送前进行表单预验证
      this.$refs.addAttrFormRef.validate(async (valid) => {
        if (!valid) {
          return this.$message.info("请检查内容后重试");
        }
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addAttrForm.attr_name,
            attr_sel: this.activeName,
          }
        );
        if (res.meta.status !== 201) return this.$message.error("添加失败");
        this.$message.success("添加成功");
        this.addAttrDialogVisible = false;
        this.getParamsData();
      });
    },

    // 点击编辑 展示修改参数内容对话框
    async showEditDialog(currentCateId, currentAttrId) {
      // 保存相应id
      this.currentCateId = currentCateId;
      this.currentAttrId = currentAttrId;
      // 根据 id 获取对应参数

      const { data: res } = await this.$http.get(
        `categories/${currentCateId}/attributes/${currentAttrId}`,
        { attr_sel: this.activeName }
      );
      //   console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("修改参数失败");
      } else {
        this.editAttrForm.attr_name = res.data.attr_name;
        this.editAttrDialogVisible = true;
      }
    },

    // 点击确定发送修改参数请求
    sendEditAttrForm() {
      // 请求前进行表单预验证
      this.$refs.editAttrFormRef.validate(async (valid) => {
        if (!valid) return this.$message.info("请检查内容后重试");
        const { data: res } = await this.$http.put(
          `categories/${this.currentCateId}/attributes/${this.currentAttrId}`,
          {
            attr_name: this.editAttrForm.attr_name,
            attr_sel: this.activeName,
          }
        );
        if (res.meta.status !== 200) return this.$message.error("修改失败");
        this.$message.success("修改成功");
        this.editAttrDialogVisible = false;
        this.getParamsData();
      });
    },

    // 监听修改参数对话框关闭事件
    editAttrDialogClosed() {
      this.$refs.editAttrFormRef.resetFields();
    },

    //点击删除 移除相应参数
    async deleteParams(currentCateId, currentAttrId) {
      // 询问用户是否确认删除
      const value = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (value === "cancel") return this.$message.info("已取消删除");
      const { data: res } = await this.$http.delete(
        `categories/${currentCateId}/attributes/${currentAttrId}`
      );
      //    console.log(res)
      if (res.meta.status !== 200) return this.$message.error("删除失败");
      this.$message.success("删除成功");
      this.getParamsData();
    },

    // 监听文本框事件
    async handleInputConfirm(row) {
      // 判断输入内容是否合法
      if (row.inputValue.trim().length === 0) {
        row.inputVisible = false;
        return;
      }
      row.attr_vals.push(row.inputValue.trim());
      // 将修改后的数据请求到后台数据库
      this.saveAttrVals(row);

      row.inputValue = "";
      row.inputVisible = false;
    },

    // 监听 tig 按钮点击事件
    showInput(row) {
      row.inputVisible = true;
      // 文本框自动获取焦点
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    // 点击标签 删除对应标签参数
    closedTag(row, index) {
      row.attr_vals.splice(index, 1);
      // 将修改后的数据请求到后台数据库
      this.saveAttrVals();
    },

    // 对 attr_vals 的操作 发起修改请求
    async saveAttrVals(row) {
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: this.activeName,
          attr_vals: row.attr_vals.join(","),
        }
      );
      if (res.meta.status !== 200) return this.$message.error("修改失败");
      this.$message.success("修改成功");
    },
  },

  computed: {
    isDisable() {
      // 根据是否选择了三级分类 判断“添加参数”与“添加属性”按钮的禁用状态
      if (this.selectedCateId.length !== 0) {
        return false;
      } else {
        return true;
      }
    },

    // 当前选中的三级分类 id
    cateId() {
      if (this.selectedCateId.length === 3) {
        return this.selectedCateId[2];
      }
      return null;
    },
  },
};
</script>
    
<style lang='less' scoped>
.el-row {
  margin: 15px 0;
}

.el-tag {
  margin: 10px;
}
.input-new-tag {
  width: 120px;
}
</style>